package com.it.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.it.common.FrameResp;
import com.it.model.Book;
import com.it.model.Chapter;
import com.it.model.ChapterVo;
import com.it.model.TreeViewNode;
import com.it.service.IBookService;
import com.it.service.IChapterService;
import com.it.utils.Logs;
import com.it.utils.Pair;
import com.it.utils.R;
import com.it.utils.StringUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.util.NumberUtils;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * @desc:
 * @author: panxiyi
 * @date: 2023/6/4 11:44 下午
 */

@RestController
@RequestMapping("/chapter")
public class ChapterController {


    @Autowired
    private IChapterService chapterService;

    @Autowired
    private IBookService bookService;

    private final ResourceLoader resourceLoader;


    @Value("${spring.web.resources.static-locations}")
    private String resourcesLocation;


    public ChapterController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }


    @GetMapping(value = "get_all")
    public FrameResp getAll() {
        return FrameResp.RET_SUCCESS(chapterService.list());
    }

    public static boolean isStringNumeric(String str) {
        if (str == null || str.isEmpty()) {
            return false;
        }
        try {
            new BigDecimal(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    @GetMapping(value = "get_tree_view")
    public FrameResp getAllTrewView(@RequestParam(value = "book_id", defaultValue = "0") Long bookId) {

        Book byId = bookService.getById(bookId);

        QueryWrapper<Chapter> qw = new QueryWrapper<>();
        qw.eq("book_id", bookId);
        List<Chapter> list = chapterService.list(qw);

        TreeMap<Integer, Chapter> treeMap = new TreeMap<>();
        Integer notStrIndex = 100;
        for (Chapter chapter : list) {
            String first2Str = chapter.getChapterName().substring(0, 2);
            if (isStringNumeric(first2Str)) {
                Integer index = Integer.valueOf(first2Str);
                treeMap.put(index, chapter);
            } else {
                treeMap.put(notStrIndex++, chapter);
            }
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        List<TreeViewNode> newList = new ArrayList<>();
        if (null != byId && !CollectionUtils.isEmpty(list)) {
            hashMap.put("id", 1);
            hashMap.put("title", byId.getName());
            int i = 10;
            Set<Map.Entry<Integer, Chapter>> entries = treeMap.entrySet();
            for (Map.Entry<Integer, Chapter> entry : entries) {
                Chapter chapter = entry.getValue();
                TreeViewNode treeViewNode = new TreeViewNode();
                treeViewNode.setId(i++);
                String title = chapter.getChapterName().replace(".html", "");

                treeViewNode.setTitle(title);
                treeViewNode.setUrl(chapter.getChapterPath());
                newList.add(treeViewNode);
            }
            hashMap.put("children", newList);
        }
        if (hashMap.size() > 0) {
            return FrameResp.RET_SUCCESS(Arrays.asList(hashMap));
        }
        return FrameResp.RET_SUCCESS();
    }


    @GetMapping("get_by_id")
    public FrameResp getById(@RequestParam(name = "id") Long id) {
        return FrameResp.RET_SUCCESS(chapterService.getById(id));
    }

//    @GetMapping("get_test")
//    public FrameResp getTest(@RequestParam(name = "path") String path) {
//        // 创建完整的资源路径
//        path = path.replaceAll("/static", "");
//        String fullPath = "file:" + resourcesLocation + path;
//
//        // 通过ResourceLoader加载文件
//        Resource resource = resourceLoader.getResource(fullPath);
//        // 如果资源存在，返回资源内容
//        return FrameResp.RET_SUCCESS(resource);
//    }

    @GetMapping("get_file_content")
    public ResponseEntity<byte[]> getTest(@RequestParam(name = "path") String path) throws IOException {
        // 创建完整的资源路径
        path = path.replaceAll("/static/", "");
        String fullPath = "file:" + resourcesLocation + path;

        // 通过ResourceLoader加载文件
        Resource resource = resourceLoader.getResource(fullPath);
        if (!resource.exists()) {
            // 如果资源不存在，则返回 404 错误
            Logs.common.info(Pair.of("message", "get_file_content fail"));
            return ResponseEntity.notFound().build();
        }
        // 如果资源存在，返回资源内容
        // 读取文件内容为字节数组
        byte[] fileContent = StreamUtils.copyToByteArray(resource.getInputStream());
        Logs.common.info(Pair.of("message", "get_file_content"), Pair.of("name", resource.getFilename()), Pair.of("file length", fileContent.length));
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                .body(fileContent);
    }
}
